package com.bonc.modules.rpt.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bonc.common.utils.Result;
import com.bonc.modules.rpt.param.FixParam;
import com.bonc.modules.rpt.param.UserColumnParam;
import com.bonc.modules.rpt.result.DynamicColumnResult;
import com.bonc.modules.rpt.service.DynamicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author jinlong
 * @date 2021/7/20
 */
@Controller
@RequestMapping("/rpt/dnm")
public class DynamicController {


    @Autowired
    private DynamicService dynamicService;

    /**
     * 获取可选字段
     */
    @GetMapping("/configColumn")
    @ResponseBody
    public Result configColumn(UserColumnParam userColumnParam) throws SQLException {
        List<DynamicColumnResult> configTableColumns = dynamicService.getConfigTableColumns(userColumnParam.getTableName());
        return Result.ok().put("data",configTableColumns);
    }


    /**
     * 获取用户自定义字段
     * @param userColumnParam
     * @return
     * @throws SQLException
     */
    @GetMapping("/userColumn")
    @ResponseBody
    public Result userColumn(UserColumnParam userColumnParam) {
        List userColumn = dynamicService.getUserColumn(userColumnParam.getTableName());
        return Result.ok().put("data", userColumn);
    }


    /**
     * 修改用户自定义字段
     * @param userColumnParam
     * @return
     */
    @GetMapping("/modifyUserColumn")
    @ResponseBody
    public Result modifyUserColumn(UserColumnParam userColumnParam) {
        boolean result = dynamicService.modifyUserColumn(userColumnParam);
        return Result.instance(result);
    }

    @GetMapping("/maxDate")
    @ResponseBody
    public Result maxDate(FixParam fixParam) {

        String maxDate = dynamicService.getMaxDate(fixParam.getTableName());

        return Result.ok().put("maxDate", maxDate);
    }

    @GetMapping("/page")
    @ResponseBody
    public Result page(FixParam fixParam) {
        Page page = dynamicService.queryPage(fixParam);
        return Result.ok().put("page", page);
    }


    @GetMapping("/data")
    @ResponseBody
    public Result data(FixParam fixParam) {
        List data = dynamicService.queryData(fixParam);
        return Result.ok().put("list", data);
    }

    /**
     * 文件下载并且失败的时候返回json（默认失败了会返回一个有部分数据的Excel）
     *
     */
    @GetMapping("/excel")
    public void downloadFailedUsingJson(HttpServletResponse response, FixParam fixParam) throws IOException {
        List<Map> data = dynamicService.queryData(fixParam);
        List<DynamicColumnResult> defaultTableColumns = dynamicService.getDefaultTableColumns(fixParam.getTableName());
        List<DynamicColumnResult> userColumn = dynamicService.getUserColumn(fixParam.getTableName());
        List<DynamicColumnResult> dynamicColumnResults = CollUtil.addAllIfNotContains(defaultTableColumns, userColumn);

        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(fixParam.getRptName(), "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream()).head(head(dynamicColumnResults)).autoCloseStream(Boolean.TRUE).sheet("sheet1")
                    .doWrite(dataList(data,dynamicColumnResults));
        } catch (Exception e) {
            e.printStackTrace();
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(JSONUtil.toJsonStr(Result.error("下载文件失败,请联系管理员")));
        }
    }

    private List<List<String>> head(List<DynamicColumnResult> userColumnParamList) {
        List<List<String>> list = new ArrayList<>();
        for (DynamicColumnResult dynamicColumnResult : userColumnParamList) {
            List<String> head = new ArrayList<>();
            head.add(dynamicColumnResult.getColumnDesc());
            list.add(head);
        }
        return list;
    }

    private  List<List<Object>> dataList(List<Map> dataList,List<DynamicColumnResult> userColumnParamList) {
        return dataList.stream().map(data -> {
            List<Object> dataObj = new ArrayList<>();
            for (DynamicColumnResult dynamicColumnResult : userColumnParamList) {
                dataObj.add(data.get(dynamicColumnResult.getColumnName()));
            }
            return dataObj;
        }).collect(Collectors.toList());
    }
}